package MysqlProvider


import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"strings"
	"Volta/Config"
)

type Mysql struct {
	 Conn *sql.DB
}

var GoMysql = Mysql{}

func (mysqlModel *Mysql) Connect() bool{
	//构建连接："用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
	path := strings.Join([]string{Config.Database.DbUsername, ":", Config.Database.DbPassword, "@tcp(",Config.Database.DbHost, ":", Config.Database.DbPort, ")/", Config.Database.DbDatabase, "?charset=utf8&multiStatements=true"}, "")

	mysqlModel.Conn, _ = sql.Open("mysql", path)
	//设置数据库最大连接数
	mysqlModel.Conn.SetConnMaxLifetime(1000)
	//设置上数据库最大闲置连接数
	mysqlModel.Conn.SetMaxIdleConns(10)
	//验证连接
	if err := mysqlModel.Conn.Ping(); err != nil{
		fmt.Println("open database fail")
		return false
	}
	return true
}

func (mysqlModel *Mysql) DB() *sql.DB {
	return mysqlModel.Conn
}

func (mysqlModel *Mysql) ToSlice(row *sql.Rows) []map[string]string {
	cols,_ := row.Columns()
	var res []map[string]string = make([]map[string]string,0)
	var scans []interface{} = make([]interface{},len(cols))
	var vals []interface{} = make([]interface{},len(cols))
	for k, _ := range scans {
		scans[k] = &vals[k]
	}
	for row.Next(){
		var coldata map[string]string = make(map[string]string)
		row.Scan(scans...)
		for k,v := range cols {
			switch vals[k].(type) {
			case []uint8:
				coldata[v] = string(vals[k].([]uint8))
			case nil:
				coldata[v] = ""
			}
		}
		res = append(res,coldata)
	}
	return res
}
